﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Linq.Dynamic;
using System.Web.Mvc;
using SDT.Model;
using SDT.Lib.Common;
using SDT.Site.Properties;
using SDT.Site.ViewModels;
using SDT.Lib.Paging;
using System.Web.UI.WebControls;
using System.IO;
using System.Data.Linq;
using SDT.Lib.Helpers;
using System.Web.Security;
using System.Configuration;
using System.Collections.Specialized;

namespace SDT.Site.Controllers
{
    public class ShoppingController : Controller
    {
        //
        // GET: /Shopping/
        SDTDataContext db = new SDTDataContext();
        [HttpPost]
        public ActionResult Create()
        {
            var cart = Session[Messages.Cart] != null ? (CartViewModels)Session[Messages.Cart] : new CartViewModels();
            var productID = Request["hdProductID"] != null && Request["hdProductID"] != string.Empty ?
                Utils.ParseInt(Request["hdProductID"]) : -1;
            var number = Request["txtQuantity"] != null && Request["txtQuantity"] != string.Empty && Utils.ParseInt(Request["txtQuantity"])>0 ?
                Utils.ParseInt(Request["txtQuantity"]) : 1;
            var p = db.Products.Where(e => e.ID == productID).SingleOrDefault();

            if (p != null)
            {
                ProductInCart pincart = new ProductInCart();
                pincart.Product = p;
                pincart.Quantity = number;

                if (cart.ProductInCarts == null) cart.ProductInCarts = new List<ProductInCart>();
                if (cart.ProductInCarts.Count > 0)
                {
                    var has = cart.ProductInCarts.Where(e => e.Product.ID == productID).FirstOrDefault();
                    if (has != null)
                    {
                        cart.ProductInCarts.Remove(has);
                    }
                }
                cart.ProductInCarts.Add(pincart);
            }
            Session[Messages.Cart] = cart;
            return RedirectToAction("cart");
        }
        public ActionResult Cart()
        {
            var cart = Session[Messages.Cart] != null ? (CartViewModels)Session[Messages.Cart] : new CartViewModels();
            cart.Cities = db.Cities.ToList();
            cart.Districts = db.Districts.ToList();
            cart.Sexuals = Utils.StringToDictionaryIntString(Settings.Default.CustomerSexual, ",");
            cart.Customer = User.Identity.Name != null ? CustomerManager.GetUser(User.Identity.Name) : null;
            cart.Payments = db.Payments.OrderBy(e => e.Priority).ToList();
            cart.Cities = db.Cities.ToList();
            cart.Districts = cart.Customer != null && cart.Customer.CityID > 0 ?
                db.Districts.Where(e => e.CityID == cart.Customer.CityID).ToList() : new List<District>();
            return View(cart);
        }
        public ActionResult Delete(int id)
        {
            var cart = Session[Messages.Cart] != null ? (CartViewModels)Session[Messages.Cart] : new CartViewModels();
            if (cart.ProductInCarts.Count > 0)
            {
                var has = cart.ProductInCarts.Where(e => e.Product.ID == id).FirstOrDefault();
                if (has != null)
                {
                    cart.ProductInCarts.Remove(has);
                }
            }
            Session[Messages.Cart] = cart;
            if (cart.ProductInCarts.Count > 0)
            {
                return RedirectToAction("cart");
            }
            else
            {
                return RedirectToAction("index", "product");
            }
        }
        [HttpPost]
        public ActionResult Updated()
        {
            var cart = Session[Messages.Cart] != null ? (CartViewModels)Session[Messages.Cart] : new CartViewModels();
            if (cart.ProductInCarts.Count > 0)
            {
                foreach (var item in cart.ProductInCarts)
                {
                    var number = Utils.ParseInt(Request["quantityList" + item.Product.ID]);
                    item.Quantity = number;
                }
            }
            Session[Messages.Cart] = cart;
            return RedirectToAction("cart");
        }
        [HttpPost]
        public ActionResult Order(CartViewModels cart)
        {
            try
            {
                if (Request["CaptchaText"].ToLower() == HttpContext.Session["captchastring"].ToString().ToLower())
                {
                    cart = Session[Messages.Cart] != null ? (CartViewModels)Session[Messages.Cart] : new CartViewModels();
                    cart.Order = new Order();
                    UpdateModel(cart);
                    cart.Customer = db.Customers.Where(e => e.UserName == User.Identity.Name).SingleOrDefault();
                    if (cart.ProductInCarts.Count > 0 && cart.Customer != null)
                    {
                        cart.Order.Customer = cart.Customer;
                        cart.Order.AddDate = DateTime.Now;
                        cart.Order.City = db.Cities.Where(e => e.ID == Utils.ParseInt(Request["ddlOrderCity"])).SingleOrDefault();
                        cart.Order.District = db.Districts.Where(e => e.ID == Utils.ParseInt(Request["ddlOrderDistrict"])).SingleOrDefault();

                        var d = Request["txtReceiveDate"] != null ? Utils.ParseDateTime(Request["txtReceiveDate"].ToString(), new System.Globalization.CultureInfo("vi-VN")) : DateTime.Now;
                        var h = Request["txtReceiveHour"] != null ? Utils.ParseInt(Request["txtReceiveHour"]) : 0;
                        var m = Request["txtReceiveMinute"] != null ? Utils.ParseInt(Request["txtReceiveMinute"]) : 0;
                        d = d.AddHours(h);
                        d = d.AddMinutes(m);
                        cart.Order.OrderName = "Hóa đơn mua hàng của " + cart.Order.ReFullName;
                        cart.Order.ReceiveDate = d;
                        cart.Order.ReEmail = cart.Customer.Email;
                        cart.Order.Status = OrderStatus.New;
                        cart.Order.PaymentID = Utils.ParseInt(Request["rdoPayment"]);
                        cart.Order.SeAddress = cart.Customer.Address;
                        cart.Order.SeEmail = cart.Customer.Email;
                        cart.Order.SePhone = cart.Customer.MobilePhone;
                        cart.Order.SeFullName = cart.Customer.FullName;
                        cart.Order.TypeID = OrderType.Normal;
                        //Tính shipping
                        decimal total = 0;                        
                        db.Orders.InsertOnSubmit(cart.Order);
                        db.SubmitChanges();
                        var number_products=0;
                        foreach (var item in cart.ProductInCarts)
                        {
                            var dt = new OrderDetail();
                            dt.Order = cart.Order;
                            dt.Product = db.Products.Where(e => e.ID == item.Product.ID).SingleOrDefault();
                            dt.Price = dt.Product.UnitPrice.HasValue ? dt.Product.UnitPrice.Value : 0;
                            dt.Quantity = item.Quantity > 0 ? item.Quantity : 1;
                            dt.DiscountPercent = item.Product.DiscountPercent;
                            dt.DiscountValue = item.Product.DiscountValue;
                            db.OrderDetails.InsertOnSubmit(dt);
                            total += dt.Price * dt.Quantity;
                            number_products+=dt.Quantity;
                        }
                        var products = cart.ProductInCarts.Select(e => e.Product).ToList();
                        var shipVal = SDT.Model.OrderManager.Getshipping(products, number_products);
                        cart.Order.ShippingValue = shipVal;
                        cart.Order.TotalValue = total + shipVal;
                        db.SubmitChanges();
                        Session[Messages.Cart] = null;
                    }
                    if (Utils.ParseInt(Request["rdoPayment"]) == PaymentMethod.Nganluong)
                    {
                        var total = cart.ProductInCarts.Sum(e => e.Product.UnitPrice * e.Quantity);

                        var url = NganluongPaymentManager.buildCheckoutUrl(Settings.Default.SiteRootUrl+"shopping/validatenganluong", ConfigurationManager.AppSettings["ReceiveFromMail"], "Hóa đơn mua hàng của " + cart.Customer.FullName != null ? cart.Customer.FullName : cart.Customer.Email, cart.Order.ID.ToString(), total.ToString());
                        return Redirect(url);
                    }
                    else if (Utils.ParseInt(Request["rdoPayment"]) == PaymentMethod.Baokim)
                    {
                        var total = cart.ProductInCarts.Sum(e => e.Product.UnitPrice * e.Quantity);

                        var url = BaokimPaymentManager.createRequestUrl(cart.Order.ID.ToString(), "Hóa đơn mua hàng của " + cart.Customer.FullName != null ? cart.Customer.FullName : cart.Customer.Email, total.ToString(), string.Empty, string.Empty, string.Empty, "", "", "");
                        return Redirect(url);
                    }
                    else if (Utils.ParseInt(Request["rdoPayment"]) == PaymentMethod.OnePay)
                    {
                        var url = OnePayManager.BuildOnepayCheckoutUrl(Settings.Default.SiteRootUrl, cart.Order,false);
                        return Redirect(url);
                    }
                    else if (Utils.ParseInt(Request["rdoPayment"]) == PaymentMethod.OnePayWorld)
                    {
                        var url = OnePayManager.BuildOnepayCheckoutUrlWorld(Settings.Default.SiteRootUrl, cart.Order, false);
                        return Redirect(url);
                    }
                    return View("Success");
                }
                else
                {
                    ViewData[Messages.MessageInfo] = Messages.ERR_CAPTCHA_VALIDATE;
                    return View();
                }
            }
            catch (Exception exp)
            {
                ErrorLog.WriteLog(exp);
                return View("Fail");
            }
        }
        public ActionResult ValidateNganluong()
        {
            try
            {
                var error = Request["error_text"];
                if (error != null && error != string.Empty && error != "00")
                {
                    return View("Fail");
                }
                var paidYN = NganluongPaymentManager.verifyPaymentUrl(Request["transaction_info"], Request["order_code"],
                    Request["price"], Request["payment_id"], Request["payment_type"], Request["error_text"], Request["secure_code"]);
                if (paidYN == true)
                {
                    var orderID = Utils.ParseInt(Request["order_code"]);
                    if (orderID > 0)
                    {
                        var o = db.Orders.Where(e => e.ID == orderID).SingleOrDefault();
                        if (o != null)
                        {
                            o.Status = OrderStatus.Paid;
                            db.SubmitChanges();
                        }
                    }
                    else {
                        return View("Fail");
                    }
                }
                return View("Success");
            }
            catch (Exception exp)
            {
                ErrorLog.WriteLog(exp);
                return View("Fail");
            }
        }
        public ActionResult ValidateBaokim(NameValueCollection get_params)
        {
            try
            {
                var error = Request["error_text"];
                if (error != null && error != string.Empty && error != "00")
                {
                    return View("Fail");
                }
                var paidYN = NganluongPaymentManager.verifyPaymentUrl(Request["transaction_info"], Request["order_code"],
                    Request["price"], Request["payment_id"], Request["payment_type"], Request["error_text"], Request["secure_code"]);
                if (paidYN == true)
                {
                    var orderID = Utils.ParseInt(Request["order_code"]);
                    if (orderID > 0)
                    {
                        var o = db.Orders.Where(e => e.ID == orderID).SingleOrDefault();
                        if (o != null)
                        {
                            o.Status = OrderStatus.Paid;
                            db.SubmitChanges();
                        }
                    }
                    else
                    {
                        return View("Fail");
                    }
                }
                return View("Success");
            }
            catch (Exception exp)
            {
                ErrorLog.WriteLog(exp);
                return View("Fail");
            }
        }
        
        public ActionResult ValidateOnePay()
        {
            try
            {
                string SECURE_SECRET = OnePayPayment.Hashcode;
                string hashvalidateResult = "";
                // Khoi tao lop thu vien
                VPCRequest conn = new VPCRequest("http://onepay.vn");
                conn.SetSecureSecret(SECURE_SECRET);
                // Xu ly tham so tra ve va kiem tra chuoi du lieu ma hoa
                hashvalidateResult = conn.Process3PartyResponse(Request.QueryString);

                // Lay gia tri tham so tra ve tu cong thanh toan
                String vpc_TxnResponseCode = conn.GetResultField("vpc_TxnResponseCode", "Unknown");
                string amount = conn.GetResultField("vpc_Amount", "Unknown");
                string localed = conn.GetResultField("vpc_Locale", "Unknown");
                string command = conn.GetResultField("vpc_Command", "Unknown");
                string version = conn.GetResultField("vpc_Version", "Unknown");
                string cardBin = conn.GetResultField("vpc_Card", "Unknown");
                string orderInfo = conn.GetResultField("vpc_OrderInfo", "Unknown");
                string merchantID = conn.GetResultField("vpc_Merchant", "Unknown");
                string authorizeID = conn.GetResultField("vpc_AuthorizeId", "Unknown");
                string merchTxnRef = conn.GetResultField("vpc_MerchTxnRef", "Unknown");
                string transactionNo = conn.GetResultField("vpc_TransactionNo", "Unknown");
                string txnResponseCode = vpc_TxnResponseCode;
                string message = conn.GetResultField("vpc_Message", "Unknown");

                // Sua lai ham check chuoi ma hoa du lieu
                var orderID = Utils.ParseInt(orderInfo);
                var order = db.Orders.Where(e => e.ID == orderID).SingleOrDefault();
                if (hashvalidateResult == "CORRECTED" && txnResponseCode.Trim() == "0")
                {
                    order.Status = OrderStatus.Paid;
                    db.SubmitChanges();
                    return View("Success");
                }
                else if (hashvalidateResult == "INVALIDATED" && txnResponseCode.Trim() == "0")
                {
                    order.Status = OrderStatus.PendingOnline;
                    db.SubmitChanges();
                    return View("Success");
                }
                else
                {
                    order.Status = OrderStatus.TransactionFail;
                    db.SubmitChanges();
                }
                return View("TransactionFail");
            }
            catch (Exception exp)
            {
                ErrorLog.WriteLog(exp);
                return View("Fail");
            }
        }
        public ActionResult ValidateOnePayWorld()
        {
            try
            {
                string SECURE_SECRET = OnePayPaymentWorld.Hashcode;
                string hashvalidateResult = "";
                // Khoi tao lop thu vien
                VPCRequest conn = new VPCRequest("http://onepay.vn");
                conn.SetSecureSecret(SECURE_SECRET);
                // Xu ly tham so tra ve va kiem tra chuoi du lieu ma hoa
                hashvalidateResult = conn.Process3PartyResponse(Request.QueryString);
                // Lay gia tri tham so tra ve tu cong thanh toan
                String vpc_TxnResponseCode = conn.GetResultField("vpc_TxnResponseCode", "Unknown");
                string amount = conn.GetResultField("vpc_Amount", "Unknown");
                string localed = conn.GetResultField("vpc_Locale", "Unknown");
                string command = conn.GetResultField("vpc_Command", "Unknown");
                string version = conn.GetResultField("vpc_Version", "Unknown");
                string cardType = conn.GetResultField("vpc_Card", "Unknown");
                string orderInfo = conn.GetResultField("vpc_OrderInfo", "Unknown");
                string merchantID = conn.GetResultField("vpc_Merchant", "Unknown");
                string authorizeID = conn.GetResultField("vpc_AuthorizeId", "Unknown");
                string merchTxnRef = conn.GetResultField("vpc_MerchTxnRef", "Unknown");
                string transactionNo = conn.GetResultField("vpc_TransactionNo", "Unknown");
                string acqResponseCode = conn.GetResultField("vpc_AcqResponseCode", "Unknown");
                string txnResponseCode = vpc_TxnResponseCode;
                string message = conn.GetResultField("vpc_Message", "Unknown");

                // Sua lai ham check chuoi ma hoa du lieu
                var orderID = Utils.ParseInt(orderInfo);
                var order = db.Orders.Where(e => e.ID == orderID).SingleOrDefault();
                if (hashvalidateResult == "CORRECTED" && txnResponseCode.Trim() == "0")
                {
                    order.Status = OrderStatus.Paid;
                    db.SubmitChanges();
                    return View("Success");
                }
                else if (hashvalidateResult == "INVALIDATED" && txnResponseCode.Trim() == "0")
                {
                    order.Status = OrderStatus.PendingOnline;
                    db.SubmitChanges();
                    return View("Pending");
                }
                else
                {
                    order.Status = OrderStatus.TransactionFail;
                    db.SubmitChanges();
                }
                return View("TransactionFail");
            }
            catch (Exception exp)
            {
                ErrorLog.WriteLog(exp);
                return View("Fail");
            }
        }
    }
}
